﻿using System;
using System.Linq;
using System.Collections.Generic;
using Microsoft.Phone.Controls;
using SoftwareLogistics.SharepointClient.Models;
using SoftwareLogistics.SharepointClient.Library;
using System.Text;
using System.Windows;

namespace SoftwareLogistics.SharepointClient
{
    public partial class DataForm : PhoneApplicationPage
    {
        private SPFormData _formData;

        public DataForm()
        {            
            InitializeComponent();
        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            var _dataRowId = new Guid(NavigationContext.QueryString["id"]);
            _formData = Common.GetFromNavDictionary<SPFormData>(_dataRowId);

            PageTitle.Text = Common.ListMetaData[_formData.ListName].Title;

            FormFields.ItemsSource = _formData.GetFormFields();

            base.OnNavigatedTo(e);
        }

        protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
        {


            base.OnNavigatedFrom(e);
        }

        private void SaveButton_Click(object sender, EventArgs e)
        {
            var fields = FormFields.ItemsSource as IEnumerable<SPField>;
            var errors = _formData.ProcessFields(fields);

            if (errors.Count() > 0)
            {
                var bldr = new StringBuilder();
                foreach (var error in errors)
                    bldr.AppendLine(error.Message);

                MessageBox.Show(bldr.ToString(), "Please correct the following errors.", MessageBoxButton.OK);

                return;
            }

            ProgressBar.Visibility = Visibility.Visible;
            ProgressBar.IsIndeterminate = true;

            var service = new Services.SPListService();
            service.RecordUpdated += (s, a) =>
            {
                Dispatcher.BeginInvoke(() =>
                {
                    ProgressBar.Visibility = Visibility.Collapsed;
                    ProgressBar.IsIndeterminate = false;
                    NavigationService.GoBack();
                });
            };

            service.UpdateRecord(_formData.IsEdit, _formData.ListName, fields);
        }
    }
}